package chen.web.firewall;

import java.util.Map;
import java.util.Set;

public abstract class AbstractTable <T, P> {
	
	protected Map<T, Object> blackList = new java.util.concurrent.ConcurrentHashMap<T, Object>();
	protected Map<T, Object> whiteList = new java.util.concurrent.ConcurrentHashMap<T, Object>();
	
	public static enum Type{Deny, Allow}
	
	public void addRule(T t, Type type){
		if(type == Type.Deny)
			blackList.put(t, "");
		else if(type == Type.Allow)
			whiteList.put(t, "");
		else 
			throw new IllegalArgumentException();
	}
	
	public Set<T> rules(Type type){
		if(type == Type.Deny){
			return blackList.keySet();
		} else if(type == Type.Allow){
			return whiteList.keySet();
		}
		throw new IllegalArgumentException();
	}
	
	public void removeRule(T t, Type type){
		if(type == Type.Deny){
			blackList.remove(t);
		} else if(type == Type.Allow){
			whiteList.remove(t);
		} else
		throw new IllegalArgumentException();
	}
	
	public void removeAll(Type type){
		if(type == Type.Deny){
			blackList.clear();;
		} else if(type == Type.Allow){
			whiteList.clear();
		} else
		throw new IllegalArgumentException();
	}
	
	public boolean accept(P obj){
		if(match(obj, Type.Deny)){
			return false;
		}
		//若白名单为空则不使用白名单
		if(!whiteList.isEmpty() && !match(obj, Type.Allow)){
			return false;
		}
		return true;
	}
	
	protected boolean match(P obj, Type type){
		if(type == Type.Deny){
			return blackList.containsKey(obj);
		} else if(type == Type.Allow){
			return whiteList.containsKey(obj);
		}
		throw new IllegalArgumentException();
	}

}
